package com.cskt.petproject178.controller;
import com.cskt.petproject178.pojo.Authened;
import com.cskt.petproject178.pojo.vo.ResultVO;
import com.cskt.petproject178.pojo.vo.ShoppingCartVO;
import com.cskt.petproject178.pojo.vo.StatusEnum;
import com.cskt.petproject178.pojo.vo.UserInfoVO;
import com.cskt.petproject178.service.ShoppingCartService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单控制器
 *
 * @author 27013
 **/



@RestController
@RequestMapping(value = "/oms")
public class ShoppingCartController {
    private static final Logger log = LoggerFactory.getLogger(ShoppingCartController.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private ShoppingCartService shoppingCartService;

    @PostMapping(value = "/cart/add")
    @Authened
    public ResultVO<Void> addOrderItem(@RequestParam(value = "skuId") Long skuId, @RequestParam(value = "num") Integer num, @RequestHeader(value = "Token",required = false) String token) {
        String tokenKeyUser = "pet:token:"+token;
        String userStr = stringRedisTemplate.opsForValue().get(tokenKeyUser);
        //反序列化成为user对象
        UserInfoVO user;
        try {
          user=objectMapper.readValue(userStr,UserInfoVO.class);
        } catch (JsonProcessingException e) {
            log.error("反序列为user对象时出错", e);
            return  ResultVO.ERR(StatusEnum.COMMON_EXCEPTION);
        }
        Boolean result = shoppingCartService.getSpuProductBySkuId(skuId,user.getId(), num);
        return result? ResultVO.OK():ResultVO.ERR();
    }


    @GetMapping(value = "/cart/cartList")
    @Authened
    public ResultVO<?> getOrderItem(@RequestHeader(value = "Token") String token) {

        try {
            String tokenKey = "pet:token:"+token;
            //通过tokenKey拿到用户编号
            String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
            //反序列化成为User对象
            UserInfoVO user = objectMapper.readValue(userStr, UserInfoVO.class);
            //取出redis中的购物车数据
            Map<Object, Object> cart = stringRedisTemplate.opsForHash().entries("pet:cart:" + user.getId());
            //将map转换成list
            List<ShoppingCartVO> shoppingCartVOS = cart.entrySet().stream().map(entry -> {

                ShoppingCartVO shopping = null;
                try {
                    shopping = objectMapper.readValue((String) entry.getValue(), ShoppingCartVO.class);
                    return shopping;
                } catch (JsonProcessingException e) {
                    log.error("反序列化为ShoppingCartVO对象时出错", e);
                    return null;
                }
            }).collect(Collectors.toList());
            return ResultVO.OK(shoppingCartVOS);
        } catch (JsonProcessingException e) {
            log.error("反序列为user对象时出错", e);
            return ResultVO.ERR(StatusEnum.COMMON_EXCEPTION);
        }
    }


    @PostMapping(value = "/cart/remove")
    @Authened
    public ResultVO<?> remove(@RequestHeader(value = "Token",required = false) String token, @RequestParam(value = "skuIds") String spuIds) {
        String tokenKey="pet:token:"+token;
        //根据token获取用户id
        String[] splitCartVO = spuIds.split(",");
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        try {
            UserInfoVO user=objectMapper.readValue(userStr,UserInfoVO.class);
            //根据用户id和商品id删除购物车数据
            stringRedisTemplate.opsForHash().delete("pet:cart:"+user.getId(),splitCartVO);
            return ResultVO.OK();
        } catch (JsonProcessingException e) {
            log.error("做删除操作时的反序列化JSON到对象时出错", e);
            return ResultVO.ERR(StatusEnum.COMMON_EXCEPTION);
        }
    }


    /**
     * 根据token从redis中获取到购物车的商品数量
     * @return
     */
    @GetMapping(value = "/cart/cartCount")
    @Authened
    public ResultVO<?> cartCount(@RequestHeader(value = "Token") String token)
    {
        String tokenKey="pet:token:"+token;
        //根据tokenKey获取到用户id
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        try {
            UserInfoVO user = objectMapper.readValue(userStr, UserInfoVO.class);
            //根据用户id获取到购物车的商品数量
            Long cartCount = stringRedisTemplate.opsForHash().size("pet:cart:" + user.getId());
            Map<String,Long> map=new HashMap<>();
            map.put("cartCount",cartCount);
            return ResultVO.OK(map);
        } catch (JsonProcessingException e) {
            log.error("做获取购物车商品数量时的反序列化JSON到UserInfoVO对象时出错");
            return ResultVO.ERR(StatusEnum.COMMON_EXCEPTION);
        }
    }
}
